<template>
    <div class="app-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="left">
                <el-button link @click="goBack">
                    <el-icon><ArrowLeft /></el-icon>
                    返回商品列表
                </el-button>
                <div class="title">规格管理</div>
                <el-tag
                    type="info"
                    effect="plain"
                    class="product-name"
                >
                    {{ productStore.productInfo.productsName }}
                    
                </el-tag>
                <el-tag 
                        :type="productStore.productInfo.status === '1' ? 'success' : 'info'"
                        size="small"
                        class="ml-2"
                    >
                        {{ productStore.productInfo.status === '1' ? '在售' : '下架' }}
                    </el-tag>
            </div>
            <div class="right">
                <el-button type="primary" @click="handleAddSpec">
                    <el-icon><Plus /></el-icon>添加规格
                </el-button>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
            <el-row :gutter="20">
                <!-- 左侧规格列表 -->
                <el-col :span="8">
                    <el-card class="spec-list" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>规格列表 ({{ productStore.specifications.length }})</span>
                            </div>
                        </template>
                        <el-scrollbar height="calc(100vh - 250px)">
                            <ul class="infinite-list">
                                <li
                                    v-for="(spec, index) in productStore.specifications"
                                    :key="index"
                                    :class="{ 'spec-item': true, active: currentSpec?.id === spec.id }"
                                    @click="handleSelectSpec(spec)"
                                >
                                    <div class="spec-info">
                                        <span class="spec-name">{{ spec.name }}</span>
                                        <span class="value-count">{{ spec.values?.length || 0 }}个值</span>
                                    </div>
                                    <div class="spec-actions">
                                        <el-button type="primary" link @click.stop="handleEditSpec(spec)">
                                            <el-icon><Edit /></el-icon>
                                        </el-button>
                                        <el-button type="danger" link @click.stop="handleDeleteSpec(spec)">
                                            <el-icon><Delete /></el-icon>
                                        </el-button>
                                    </div>
                                </li>
                            </ul>
                        </el-scrollbar>
                    </el-card>
                </el-col>

                <!-- 右侧规格值列表 -->
                <el-col :span="16">
                    <el-card v-if="currentSpec" shadow="hover">
                        <template #header>
                            <div class="card-header">
                                <span>{{ currentSpec.name }} - 规格值</span>
                                <el-button type="primary" link @click="handleAddValue">
                                    <el-icon><Plus /></el-icon>添加规格值
                                </el-button>
                            </div>
                        </template>
                        <el-table :data="currentSpec.values" style="width: 100%">
                            <el-table-column type="index" label="序号" width="80" align="center" />
                            <el-table-column label="规格值" prop="value" />
                            <el-table-column label="排序" prop="sort" width="180" />
                            <el-table-column label="操作" width="180" align="center">
                                <template #default="scope">
                                    <el-button type="primary" link @click="handleEditValue(scope.row)">
                                        编辑
                                    </el-button>
                                    <el-button type="danger" link @click="handleDeleteValue(scope.row)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                    <el-empty v-else description="请选择规格" />
                </el-col>
            </el-row>

            <!-- 底部操作按钮 -->
            <div class="bottom-actions">
                <el-button type="primary" @click="handleSave">保存</el-button>
                <el-button @click="goBack">返回</el-button>
            </div>
        </div>

        <!-- 规格编辑对话框 -->
        <el-dialog
            v-model="specDialogVisible"
            :title="dialogType === 'add' ? '添加规格' : '编辑规格'"
            width="500px"
        >
            <el-form ref="specFormRef" :model="specForm" :rules="specRules" label-width="80px">
                <el-form-item label="规格名称" prop="name">
                    <el-input v-model="specForm.name" placeholder="请输入规格名称" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="specDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitSpecForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 规格值编辑对话框 -->
        <el-dialog
            v-model="valueDialogVisible"
            :title="dialogType === 'add' ? '添加规格值' : '编辑规格值'"
            width="500px"
        >
            <el-form
                ref="valueFormRef"
                :model="valueForm"
                :rules="valueRules"
                label-width="80px"
            >
                <el-form-item label="规格值" prop="value">
                    <el-input v-model="valueForm.value" placeholder="请输入规格值" />
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="valueForm.sort" :min="0" :max="999" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="valueDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitValueForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Edit, Delete, ArrowLeft } from '@element-plus/icons-vue';
import { useProductStore } from '@/store/modules/product';

const router = useRouter();
const route = useRoute();
const productStore = useProductStore();

// ===== 状态管理 =====
const currentSpec = ref(null);
const dialogType = ref('add');
const specDialogVisible = ref(false);
const valueDialogVisible = ref(false);
const specFormRef = ref(null);
const valueFormRef = ref(null);

// ===== 表单数据 =====
const specForm = ref({ name: '' });
const valueForm = ref({ value: '', sort: 0 });

// ===== 表单验证规则 =====
const specRules = {
    name: [
        { required: true, message: '请输入规格名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ]
};

const valueRules = {
    value: [
        { required: true, message: '请输入规格值', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }]
};

// ===== 规格操作方法 =====
/**
 * 选择规格
 * @param {Object} spec - 规格对象
 */
const handleSelectSpec = (spec) => {
    currentSpec.value = spec;
};

/**
 * 添加规格
 */
const handleAddSpec = () => {
    dialogType.value = 'add';
    specForm.value = { name: '' };
    specDialogVisible.value = true;
};

/**
 * 编辑规格
 * @param {Object} spec - 规格对象
 */
const handleEditSpec = (spec) => {
    dialogType.value = 'edit';
    specForm.value = { ...spec };
    specDialogVisible.value = true;
};

/**
 * 删除规格
 * @param {Object} spec - 规格对象
 */
const handleDeleteSpec = (spec) => {
    ElMessageBox.confirm('确认删除该规格吗？', '提示', {
        type: 'warning'
    }).then(() => {
        const index = productStore.specifications.findIndex(item => item.id === spec.id);
        if (index !== -1) {
            productStore.specifications.splice(index, 1);
            if (currentSpec.value?.id === spec.id) {
                currentSpec.value = null;
            }
            ElMessage.success('删除成功');
        }
    });
};

// ===== 规格值操作方法 =====
/**
 * 添加规格值
 */
const handleAddValue = () => {
    dialogType.value = 'add';
    valueForm.value = { value: '', sort: 0 };
    valueDialogVisible.value = true;
};

/**
 * 编辑规格值
 * @param {Object} value - 规格值对象
 */
const handleEditValue = (value) => {
    dialogType.value = 'edit';
    valueForm.value = { ...value };
    valueDialogVisible.value = true;
};

/**
 * 删除规格值
 * @param {Object} value - 规格值对象
 */
const handleDeleteValue = (value) => {
    ElMessageBox.confirm('确认删除该规格值吗？', '提示', {
        type: 'warning'
    }).then(() => {
        const index = currentSpec.value.values.findIndex(item => item.id === value.id);
        if (index !== -1) {
            currentSpec.value.values.splice(index, 1);
            ElMessage.success('删除成功');
        }
    });
};

// ===== 表单提交方法 =====
/**
 * 提交规格表单
 */
const submitSpecForm = async () => {
    if (!specFormRef.value) return;
    
    try {
        const valid = await specFormRef.value.validate();
        if (!valid) return;

        if (dialogType.value === 'add') {
            const newSpec = {
                id: Date.now(),
                name: specForm.value.name,
                values: []
            };
            productStore.specifications.push(newSpec);
            currentSpec.value = newSpec;
        } else {
            const spec = productStore.specifications.find(item => item.id === specForm.value.id);
            if (spec) {
                spec.name = specForm.value.name;
            }
        }

        await productStore.updateSpecifications(productStore.specifications);
        specDialogVisible.value = false;
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
    } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
        console.error('规格操作失败:', error);
    }
};

/**
 * 提交规格值表单
 */
const submitValueForm = async () => {
    if (!valueFormRef.value) return;

    try {
        const valid = await valueFormRef.value.validate();
        if (!valid) return;

        if (dialogType.value === 'add') {
            const newValue = {
                id: `${currentSpec.value.id}_${Date.now()}`,
                value: valueForm.value.value,
                sort: valueForm.value.sort
            };
            if (!currentSpec.value.values) {
                currentSpec.value.values = [];
            }
            currentSpec.value.values.push(newValue);
        } else {
            const value = currentSpec.value.values.find(item => item.id === valueForm.value.id);
            if (value) {
                value.value = valueForm.value.value;
                value.sort = valueForm.value.sort;
            }
        }

        await productStore.updateSpecifications(productStore.specifications);
        valueDialogVisible.value = false;
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
    } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
        console.error('规格值操作失败:', error);
    }
};

/**
 * 保存所有更改
 */
const handleSave = async () => {
    try {
        await productStore.updateSpecifications(productStore.specifications);
        ElMessage.success('保存成功');
        goBack();
    } catch (error) {
        ElMessage.error('保存失败');
        console.error('保存失败:', error);
    }
};

/**
 * 返回上一页
 */
const goBack = () => {
    router.go(-1);
};

// ===== 生命周期钩子 =====
onMounted(async () => {
    const productId = route.params.id;
    if (productId) {
        try {
            await productStore.loadProductDetail(productId);
            // 默认选中第一个规格
            if (productStore.specifications.length > 0) {
                currentSpec.value = productStore.specifications[0];
            }
        } catch (error) {
            ElMessage.error('加载商品规格失败');
            console.error('加载商品规格失败:', error);
        }
    }
});
</script>

<style lang="scss" scoped>
.app-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 84px);
}

.page-header {
    height: 56px;
    line-height: 56px;
    background-color: #fff;
    padding: 0 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 4px;
    margin-bottom: 16px;

    .left {
        display: flex;
        align-items: center;
        gap: 16px;

        .title {
            font-size: 16px;
            font-weight: 500;
            color: #1f2f3d;
        }

        .product-name {
            margin-left: 8px;
        }
    }
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
}

.spec-list {
    .infinite-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }

    .spec-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px;
        border-bottom: 1px solid #ebeef5;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
            background-color: #f5f7fa;
        }

        &.active {
            background-color: #ecf5ff;
        }

        .spec-info {
            display: flex;
            align-items: center;
            gap: 8px;

            .spec-name {
                font-weight: 500;
            }

            .value-count {
                color: #909399;
                font-size: 12px;
            }
        }

        .spec-actions {
            display: flex;
            gap: 8px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        &:hover .spec-actions {
            opacity: 1;
        }
    }
}

.bottom-actions {
    margin-top: 20px;
    text-align: center;
}
</style> 